from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core import serializers
from django.db.models import Q
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from datetime import datetime
from inventory.models import *

def redirect(request, url):
    return HttpResponseRedirect(url)

@login_required
def inventory_warehouse(request):
    request.warehouses = Warehouse.objects.all().order_by('name')
    request.vendor = request.session['vendor']
    return render_to_response('inventory/warehouse_home.html', {'request': request, 'styles':['warehouse_home.css'], 'scripts':[]})

#login_required
@login_required
def inventory_warehouse_delete(request, id_wh):
    wh = Warehouse.objects.get(id=id_wh)
    log = Log(id_user=request.user, action=1, id_action=wh.id, datetime=datetime.now())
    wh.delete();
    log.save()
    return redirect(request, '/warehouse/')

@login_required
def inventory_warehouse_register(request):
    wh = Warehouse(name=request.POST['warehouse_name'])
    wh.save();
    log = Log(id_user=request.user, action=0, id_action=wh.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/warehouse/')

@login_required
def inventory_itemtemplate(request):
    res = ItemTemplate.objects.all().order_by('name')
    for it in res:
        count = Item.objects.filter(sold=False, item_template=it).count()
        it.item_count = count
    request.itemtemplates = res
    request.item_cost = 0
    for it in Item.objects.filter(sold=False):
        request.item_cost += it.sale_price * it.currency.multiplier
    request.vendor = request.session['vendor']
    return render_to_response('inventory/itemtemplate_home.html', {'request': request, 'styles':['itemtemplate_home.css'], 'scripts':[]})

@login_required
def inventory_itemtemplate_register(request):
    it = ItemTemplate(name=request.POST['itemtemplate_name'], detail=request.POST['itemtemplate_detail'], minimum=request.POST['itemtemplate_stock'])
    it.save();
    log = Log(id_user=request.user, action=4, id_action=it.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/itemtemplate/')

@login_required
def inventory_itemtemplate_detail(request, id_it):
    it = ItemTemplate.objects.get(id=id_it)
    obtainments = Obtainment.objects.filter(Q(closed=False)).order_by("date")
    warehouses = Warehouse.objects.all().order_by("name")
    items = Item.objects.filter(item_template=it, sold=False).order_by("serial")
    request.itemtemplate = it
    request.obtainments = obtainments
    request.warehouses = warehouses
    request.currencies = Currency.objects.all().order_by("name")
    request.items = items
    request.vendor = request.session['vendor']
    return render_to_response('inventory/itemtemplate_detail.html', {'request': request, 'styles':['itemtemplate_detail.css'], 'scripts':[]})

@login_required
def inventory_itemtemplate_delete(request, id_it):
    it = ItemTemplate.objects.get(id=id_it)
    log = Log(id_user=request.user, action=5, id_action=it.id, datetime=datetime.now())
    it.delete()
    log.save()
    return redirect(request, '/itemtemplate/')

@login_required
def inventory_itemtemplate_itemregister(request, id_it):
    exp = request.POST['expiration']
    if exp == "":
        exp = None
    it = ItemTemplate.objects.get(id=id_it)
    obt = Obtainment.objects.get(id=request.POST['obtainment'])
    wh = Warehouse.objects.get(id=request.POST['warehouse'])
    cur = Currency.objects.get(id=request.POST['currency'])
    item = Item(warehouse=wh, item_template=it, serial=request.POST['serial'], location=request.POST['location'], expiration=exp, basic_price=request.POST['basic_price'], sale_price=request.POST['sale_price'], currency=cur, obtainment=obt)
    item.save()
    log = Log(id_user=request.user, action=5, id_action=item.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/itemtemplate/' + id_it)

@login_required
def inventory_item_delete(request, id_i, id_it):
    i = Item.objects.get(id=id_i)
    log = Log(id_user=request.user, action=7, id_action=i.id, datetime=datetime.now())
    i.delete()
    log.save()
    return redirect(request, '/itemtemplate/' + id_it)

@login_required
def inventory_item_home(request, id_i):
    i = Item.objects.get(id=id_i)
    request.item = i
    request.vendor = request.session['vendor']
    return render_to_response('inventory/item_detail.html', {'request': request, 'styles':['item_detail.css'], 'scripts':[]}) 

@login_required
def inventory_obtainment(request):
    request.obtainments = Obtainment.objects.all().order_by('-date')
    request.providers = Provider.objects.all()
    request.vendor = request.session['vendor']
    return render_to_response('inventory/obtainments.html', {'request': request, 'styles':['itemtemplate_home.css'], 'scripts':[]}) 

@login_required
def inventory_obtainment_register(request):
    prov = Provider.objects.get(id=request.POST['provider'])
    no = Obtainment(provider=prov, date=datetime.now(), comment=request.POST['comment'], closed=False)
    no.save()
    log = Log(id_user=request.user, action=21, id_action=no.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/obtainment/')

@login_required
def inventory_obtainment_close(request, id_obt):
    obt = Obtainment.objects.get(id=id_obt)
    obt.closed = True
    obt.save()
    log = Log(id_user=request.user, action=22, id_action=obt.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/obtainment/')

@login_required
def inventory_obtainment_delete(request, id_obt):
    obt = Obtainment.objects.get(id=id_obt)
    log = Log(id_user=request.user, action=22, id_action=obt.id, datetime=datetime.now())
    obt.delete()
    log.save()
    return redirect(request, '/obtainment/')

@login_required
def inventory_vinyl(request):
    request.vinyls = Vinyl.objects.all().order_by('code')
    request.warehouses = Warehouse.objects.all().order_by('name')
    request.currencies = Currency.objects.all().order_by('name')
    request.vinyls_quantity = 0
    request.vinyls_expended = 0
    request.vinyls_quantity_kg = 0
    for val in Vinyl.objects.all():
        request.vinyls_quantity += val.quantity
    for val in Vinyl.objects.all():
        request.vinyls_expended += val.quantity * val.price * val.currency.multiplier
    for val in Vinyl.objects.all():
        request.vinyls_quantity_kg += float(float(val.quantity) * float(val.size) / 4.5)
    request.vendor = request.session['vendor']
    return render_to_response('inventory/vinyl_home.html', {'request': request, 'styles':['itemtemplate_home.css'], 'scripts':[]})

@login_required
def inventory_vinyl_register(request):
    cur = Currency.objects.get(id=request.POST['vinyl_currency'])
    war = Warehouse.objects.get(id=request.POST['vinyl_warehouse'])
    v = Vinyl(code=request.POST['vinyl_code'], size=request.POST['vinyl_size'], quantity=0, price=request.POST['vinyl_price'], name=request.POST['vinyl_name'], warehouse=war, currency=cur)
    v.save()
    log = Log(id_user=request.user, action=9, id_action=v.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/vinyl/')

@login_required
def inventory_vinyl_delete(request, id_vinyl):
    v = Vinyl.objects.get(id=id_vinyl)
    log = Log(id_user=request.user, action=11, id_action=v.id, datetime=datetime.now())
    v.delete()
    log.save()
    return redirect(request, '/vinyl/')

@login_required
def inventory_vinyl_detail(request, id_vinyl):
    request.vinyl = Vinyl.objects.get(id=id_vinyl)
    request.obtainments = Obtainment.objects.filter(Q(closed=False))
    return render_to_response('inventory/vinyl_detail.html', {'request': request, 'styles':['vinyl_detail.css'], 'scripts':[]})

def inventory_vinyl_add(request, id_vinyl):
    v = Vinyl.objects.get(id=id_vinyl)
    obt = Obtainment.objects.get(id=request.POST['vinyl_add_obtainment'])
    va = VinylAdded(quantity=request.POST['vinyl_add_quantity'], vinyl=v, obtainment=obt)
    va.save()
    log = Log(id_user=request.user, action=13, id_action=va.id, datetime=datetime.now())
    v.quantity = float(v.quantity) + float((float(va.quantity) * 4.5) / float(v.size))
    v.save()
    log.save()
    return redirect(request, '/vinyl/' + id_vinyl + '/')

@login_required
def inventory_wheel(request):
    request.wheels = Wheel.objects.all().order_by('size')
    request.warehouses = Warehouse.objects.all().order_by('name')
    request.wheels_quantity = 0
    for w in Wheel.objects.all():
        request.wheels_quantity += w.quantity
    request.vendor = request.session['vendor']
    return render_to_response('inventory/wheel_home.html', {'request': request, 'styles':['itemtemplate_home.css'], 'scripts':[]})

@login_required
def inventory_wheel_register(request):
    war = Warehouse.objects.get(id=request.POST['wheel_warehouse'])
    w = Wheel(size=request.POST['wheel_size'], quantity=0, warehouse=war)
    w.save()
    log = Log(id_user=request.user, action=10, id_action=w.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/wheel/')

@login_required
def inventory_wheel_delete(request, id_wheel):
    w = Wheel.objects.get(id=id_wheel)
    log = Log(id_user=request.user, action=12, id_action=w.id, datetime=datetime.now())
    w.delete()
    log.save()
    return redirect(request, '/wheel/')

@login_required
def inventory_wheel_detail(request, id_wheel):
    request.wheel = Wheel.objects.get(id=id_wheel)
    request.obtainments = Obtainment.objects.filter(Q(closed=False))
    return render_to_response('inventory/wheel_detail.html', {'request': request, 'styles':['vinyl_detail.css'], 'scripts':[]})

@login_required
def inventory_wheel_add(request, id_wheel):
    w = Wheel.objects.get(id=id_wheel)
    obt = Obtainment.objects.get(id=request.POST['wheel_add_obtainment'])
    wa = WheelAdded(quantity=request.POST['wheel_add_quantity'], wheel=w, obtainment=obt)
    wa.save()
    log = Log(id_user=request.user, action=14, id_action=wa.id, datetime=datetime.now())
    w.quantity = int(w.quantity) + int(wa.quantity)
    w.save()
    log.save()
    return redirect(request, '/wheel/' + id_wheel + '/')

@login_required
def inventory_currency(request):
    request.currencies = Currency.objects.all().order_by('name')
    return render_to_response('inventory/currencies.html', {'request': request, 'styles':['itemtemplate_detail.css'], 'scripts':[]})
    
@login_required
def inventory_currency_register(request):
    nc = Currency(name=request.POST['name'], symbol=request.POST['symbol'], multiplier=request.POST['multiplier'])
    nc.save()
    log = Log(id_user=request.user, action=16, id_action=nc.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/currency/')

@login_required
def inventory_currency_modify(request):
    cur = Currency.objects.get(id=request.POST['currency_id'])
    mod = CurrencyModify(date=datetime.now(), previous_multiplier=cur.multiplier, current_multiplier=request.POST['new_value'], currency=cur)
    mod.save()
    log = Log(id_user=request.user, action=17, id_action=mod.id, datetime=datetime.now())
    log.save()
    cur.multiplier = request.POST['new_value']
    cur.save()
    return redirect(request, '/currency/')
    
# AJAX

@login_required
def inventory_item_search(request, text):
    all_templates = ItemTemplate.objects.filter(Q(name__contains=text) | Q(detail__contains=text))
    all_items = list(Item.objects.filter((Q(serial__contains=text) | Q(location__contains=text)) & Q(sold=False))) + list(Item.objects.filter(item_template__in=[it.id for it in all_templates]).exclude(Q(sold=True)))
    json = serializers.serialize('json', all_items, fields=('id', 'item_template', 'serial'))
    return HttpResponse(json)

@login_required
def inventory_itemtemplate_search(request, text):
    all_items = Item.objects.filter((Q(serial__contains=text) | Q(location__contains=text)) & Q(sold=False))
    all_templates = list(ItemTemplate.objects.filter(Q(name__contains=text) | Q(detail__contains=text))) + list([i.item_template for i in all_items])
    json = serializers.serialize('json', all_templates)
    return HttpResponse(json)

@login_required
def inventory_itemtemplate_load(request, id_template):
    it = Item.objects.filter(Q(item_template=id_template) & Q(sold=False))
    class LoadedItem(models.Model):
        serial = models.CharField(max_length=30, null=False, blank=False)
        warehouse = models.CharField(max_length=30, null=False, blank=False)
    items = []
    for i in it:
        aux = LoadedItem(id=i.id, serial=i.serial, warehouse=i.warehouse.name)
        items.append(aux)
    json = serializers.serialize('json', items)
    return HttpResponse(json)

@login_required
def inventory_item_get(request, id_item):
    i = Item.objects.get(id=id_item)
    t = i.item_template
    c = i.currency
    data = list([i]) + list([t]) + list([c])
    json = serializers.serialize('json', data)
    return HttpResponse(json)

@login_required
def inventory_vinyl_search(request, text):
    all_vinyls = Vinyl.objects.filter(Q(quantity__gt=0) & (Q(code__contains=text) | Q(name__contains=text) | Q(size__contains=text)))
    json = serializers.serialize('json', all_vinyls)
    return HttpResponse(json)

@login_required
def inventory_vinyl_get(request, id_vinyl):
    v = Vinyl.objects.get(id=id_vinyl)
    c = v.currency
    data = list([v]) + list([c])
    json = serializers.serialize('json', data)
    return HttpResponse(json)

@login_required
def inventory_wheel_search(request, text):
    all_wheels = Wheel.objects.filter(Q(quantity__gt=0) & Q(size__contains=text))
    json = serializers.serialize('json', all_wheels)
    return HttpResponse(json)

@login_required
def inventory_wheel_get(request, id_wheel):
    w = Wheel.objects.get(id=id_wheel)
    c = Currency.objects.all()
    data = list([w]) + list(list(c))
    json = serializers.serialize('json', data)
    return HttpResponse(json)

@login_required
def inventory_currencies(request):
    c = Currency.objects.all()
    json = serializers.serialize('json', c)
    return HttpResponse(json)
